# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
	#生成分页栏的方法，link_to_params参数传入一个hash表，存储link_to的一些基础信息
	#total_size传入总的数量，page传入当前所在的页面，size传入每页显示的数量
	def page_bar(link_to_params, total_size, page=1, size=10)
		#前后显示的页数
		max_show = 3
	
	  #是否包含最后一页
		last_page = total_size % size > 0 ? 1: 0
		#总页数
		total_page = total_size / size + last_page
		
		#下一页的序号
		next_page = (page + 1) > total_page ? total_page: (page + 1)
		#上一页的序号
		prev_page = (page - 1) < 1? 1: (page -1)
		
		#显示当前页的片段
		current_part = "当前 第#{page}页 - "
		
		middle_part = create_page_link("[#{page}]", link_to_params, page, "第#{page}页") + " "
		
		(page + 1).upto(total_page){
			|x| 
			if x == total_page
				middle_part << create_page_link("[#{x}]", link_to_params, x, "第#{x}页") + " " 
			elsif x - page <= max_show
				middle_part << create_page_link("[#{x}]", link_to_params, x, "第#{x}页") + " " 
			elsif x - page == max_show + 1
				middle_part << " ... " 
			end
		}
		
		(page - 1).downto(1){
			|x| 
			if x == 1
				middle_part = create_page_link("[#{x}]", link_to_params, x, "第#{x}页") + " " << middle_part
			elsif page - x <= max_show
				middle_part = create_page_link("[#{x}]", link_to_params, x, "第#{x}页") + " " <<middle_part
			elsif page - x == max_show + 1
				middle_part = " ... " << middle_part
			end
		}

		#添加上一页和下一页的序号
		prev_part = create_page_link("上一页", link_to_params, prev_page, "上一页") + " "
		next_part = " " + create_page_link("下一页", link_to_params, next_page, "下一页")
		
		return prev_part << current_part << middle_part << next_part
	end
	
	private
	def create_page_link(name, link_to_params, page, title)
		link_to_params[:page] = page
		link_to(name, link_to_params, :title=>title)
	end
end
